package com.plat.api.common.base;

import com.plat.api.common.RespCode;
import com.plat.api.exception.PlatException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * author ss
 * createTime 2020/5/8
 * package ${com.example.demo.controller.base}
 ***/
@Component
@Slf4j
public class App implements ApplicationContextAware {
    private static ApplicationContext ac;

    public static <T> T getBean(String name, Class<T> type) throws PlatException {
        try {
            ac.getBean(name);
        } catch (BeansException baseException) {
            throw new PlatException(RespCode.NOT_FOUND_METHOD.getCode(), baseException.getMessage());
        }
        return (T) ac.getBean(name);
    }

    public static <T> T getBean(String name) throws PlatException {
        try {
            ac.getBean(name);
        } catch (BeansException baseException) {
            throw new PlatException(RespCode.NOT_FOUND_METHOD.getCode(), baseException.getMessage());
        }
        return (T) ac.getBean(name);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        log.info("系统启动初始化spring boot");
        ac = applicationContext;
    }
}
